<template>
  <div>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="true"
      :onSyncTableData="tableChangeFun"
      :defaultSelections="selectionList"
      :onRowSelectChange="(rows) => (this.selectionList = rows)"
      :onColumnsChange="(columns) => (this.columns = columns)"
    >
    </FilterTable>
    <div style="height: 47px"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
    >
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 2)" :disabled="isAduit">确 认</multiuse-button>
      <el-button @click="closeDrawer(1)">关 闭</el-button>
    </div>
  </div>
</template>
<script>
import { getOrderBill, saveOrderBill } from '@/api/omSaleP/OrderManagement/PurchaseOrder/index.js';
import { dictionary } from '@/utils/dictMixin';
export default {
  data() {
    return {
      columns: this.createdTable(),
      fetchParams: {
        accountId: this.rowData.accountId,
        dealerCode: this.rowData.dealerCode,
        doNo: this.rowData.doNo,
      },
      fetchApi: getOrderBill,
      selectionList: [],
      isFirst: true,
      isAduit: this.rowData.orderStatus !== 21091001 && this.rowData.orderStatus !== 21091008 && this.rowData.orderStatus !== 21091009,
    };
  },
  created() {},
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  mixins: [dictionary],
  props: ['rowData'],
  methods: {
    resetFormatterNumber(arr) {
      for (let i = 0; i < arr.length; i++) {
        let billAmount = arr[i].billAmount !== null ? Number(arr[i].billAmount.toString().replaceAll(',', '')).toFixed(2) : Number(0).toFixed(2);
        let availableAmount = arr[i].availableAmount !== null ? Number(arr[i].availableAmount.toString().replaceAll(',', '')).toFixed(2) : Number(0).toFixed(2);
        arr[i].billAmount = billAmount;
        arr[i].availableAmount = availableAmount;
      }
      return arr;
    },
    tableChangeFun(val) {
      if (this.isFirst) {
        //页面数据变化重新赋值选中行项
        this.selectionList = val.filter((item) => 1 == item.isSelect);
        //console.log(this.selectionList, '页面数据变化重新赋值选中行项');
      }
      this.isFirst = false;
    },
    async closeDrawer(type) {
      this.selectionList = this.resetFormatterNumber(this.selectionList);
      if (type === 1) {
        this.$emit('close');
      } else {
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: '警告',
            message: '请选择票据',
            type: 'warning',
          });
          return;
        }
        let useMoney = 0;
        let is = false;
        for (let i in this.selectionList) {
          if (Number(this.selectionList[i].chngAmount) < 0) {
            is = true;
            break;
          }
          useMoney = useMoney + Number(this.selectionList[i].chngAmount);
        }
        if (is) {
          this.$notify({
            title: '警告',
            message: '使用金额不能小于0',
            type: 'warning',
          });
          return;
        }
        if (Number(this.rowData.afterDiscountAmount) !== useMoney) {
          this.$notify({
            title: '警告',
            message: '选择票面使用金额不等于采购价格',
            type: 'warning',
          });
          return;
        }
        //发送请求
        this.selectionList.map(
          (x) => (
            (x.doNo = this.rowData.doNo),
            (x.discountAmount = this.rowData.discountAmount),
            (x.buildRebateAmount = this.rowData.buildRebateAmount),
            (x.singleRebateAmount = this.rowData.singleRebateAmount),
            (x.afterDiscountAmount = this.rowData.afterDiscountAmount),
            (x.orderDto = this.rowData),
            (x.isRebate = this.rowData.isRebate)
          )
        );
        let res = await saveOrderBill(this.selectionList);
        if (res.resultCode === 200) {
          this.$notify({
            title: '成功',
            message: '调整成功',
            type: 'success',
          });
          this.$emit('close', this.selectionList);
        } else {
          let message = res.errMsg;
          this.$notify({
            title: '错误',
            message: message,
            type: 'error',
          });
          this.fetchParams = Object.assign({}, this.fetchParams);
        }
      }
    },
    changeNum(index, data) {
      data = this.resetFormatterNumber([data])[0];
      let chngAmount = 0;
      chngAmount = Object.is(Number(data.chngAmount), NaN) ? 0 : Number(data.chngAmount);
      data.availableAmount = data.beforeAvailableAmount - chngAmount;
      if (Number(data.availableAmount) < 0) {
        data.availableAmount = 0;
        data.chngAmount = Number(data.beforeAvailableAmount);
        if (data.chngAmount < 0) {
          data.chngAmount = 0;
        }
        this.$notify({
          title: '警告',
          message: '使用金额不能大于票面余额',
          type: 'warning',
        });
      }
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },

        {
          title: '使用金额',
          dataIndex: 'chngAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          editable: true,
          editType: 'number',
          showOverflowTooltip: false,
          editRequired: true,
          defaultEditable: true,
          onInput: (index, data) => {
            this.changeNum(index, data);
          },
        },
        {
          title: '三方票号',
          dataIndex: 'billNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '票面金额',
          dataIndex: 'billAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
          align: 'right',
        },
        {
          title: '票面可用余额',
          dataIndex: 'availableAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
          align: 'right',
        },
        {
          title: '出票时间',
          dataIndex: 'billDate',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '到期时间',
          dataIndex: 'expireDate',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
